<template>
  <div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-col :span="6" :offset="8">
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="ruleForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-col>
      
    </el-form>
  </div>
</template>


<script>
export default {
  name: "LoginView",
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {require: true, message: "用户名不能为空", trigger: 'blur'}
        ],
        password: [
          {require: true, message: "密码不能为空", trigger: 'blur'}
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          // 这里应该是请求后台的数据。再确定是否登录成功
          let url = "/account/login";
          this.$axios.post(url, {
            "userName": this.ruleForm.username,
            "password": this.ruleForm.password
          }).then(res => {
            console.log(res);
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: res.data.msg,
                duration: 1000
              })

              //登录成功后，我们得到从后端传来的token
              let token = res.headers['token'];
              //将token设置到本地
              sessionStorage.setItem("token", token);
              sessionStorage.setItem("userName", this.ruleForm.username);
              this.$router.push("/welcome");
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped lang="less">
</style>